

package com.xgit.iov.common.mybatis;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.xgit.iov.common.handler.MyTenantHandler;
import com.xgit.iov.common.handler.MyTenantSqlParser;
import com.xgit.iov.common.handler.MybatisMetaObjectHandler;
import com.xgit.iov.common.properties.TenantProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lengleng
 * @date 2020-03-14
 * <p>
 * mybatis plus 统一配置
 */
@Configuration(proxyBeanMethods = false)
public class MybatisAutoConfiguration {

	@Autowired
	private MyTenantHandler tenantHandler;

	@Autowired
	private ISqlParserFilter sqlParserFilter;

	@Autowired
	private TenantProperties tenantProperties;

	/**
	 * 分页插件
	 *
	 * @return PaginationInterceptor
	 */
	@Bean
	public PaginationInterceptor paginationInterceptor() {
		PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
		boolean enableTenant = tenantProperties.getEnable();
		//是否开启多租户隔离
		if (enableTenant) {
			MyTenantSqlParser tenantSqlParser = new MyTenantSqlParser()
				.setTenantHandler(tenantHandler);
			paginationInterceptor.setSqlParserList(CollUtil.toList(tenantSqlParser));
			paginationInterceptor.setSqlParserFilter(sqlParserFilter);
		}
		return paginationInterceptor;
	}

	/**
	 * mybatis-plus自动填充
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean
	public MetaObjectHandler mybatisMetaObjectHandler(){
		return new MybatisMetaObjectHandler();
	}

}
